import React from 'react';
import { View, DeviceEventEmitter } from 'react-native';
import { LogUtils } from 'rn-xiaobu-utils';
import { getNextBusTime, getNoticeDetail, getPrice } from '../components/Line/api/api';
import BusInfo from '../components/Line/components/BusInfo';
import BusNav from '../components/Line/components/BusNav';
import BusNotice from '../components/Line/components/BusNotice';
import BusNow from '../components/Line/components/BusNow';
import BusStaion from '../components/Line/components/BusStation/BusStation';
import BusInfoModel from '../components/Line/models/BusInfoModel';
import BusNoticeModel from '../components/Line/models/BusNoticeModel';
import Loading from '../components/public/loading';
import flex from '../configs/flex';
import ajaxAsync from '../utils/ajaxAsync';
import { defaultStackOptions } from '../utils/DefaultTitleOption';
import Error from '../components/public/error/error';

export default class Line extends React.Component {
  static navigationOptions = ({ navigation }) => {
    let option = defaultStackOptions({ navigation })
    option.headerTitle = isNaN(navigation.getParam('name')) ? navigation.getParam('name') : navigation.getParam('name') + '路'
    return option
  }
  constructor (props) {
    super(props)
    this.state = {
      lineID: '', // 线路ID
      direction: 1, // 线路方向
      startTime: '', // 首班车时间
      endTime: '', // 末班车时间
      startStation: '', // 首站
      endStation: '', // 末站
      price: '', // 票价
      lat: '', // 当前经度
      lng: '', // 当前维度
      stations: [], // 站点详情
      thisID: '', // 当前站点ID
      thisName: '', // 当前站点名称
      thisIndex: -1, // 当前站点序号
      busNowApis: [], // 当前车辆位置
      simpleDistance: [], // 当前公交列表
      showModel: true, // 显示遮罩层
      changging: true, // 正在换向
      nextTime: '', // 下一班发车时间
      notice: {}, // 公告
      modelText: '加载中···', // 遮罩文字
      segmentId: 0 // 线路独特ID
    }
    this._getParams = this._getParams.bind(this)
    this._getBusInfo = this._getBusInfo.bind(this)
    this._setIndex = this._setIndex.bind(this)
    this._getPrice = this._getPrice.bind(this)

    this.refreshLine = DeviceEventEmitter.addListener('refreshLine', () => {
      clearTimeout(this._getInterval)
      this.setState({ showModel: true, modelText: '刷新中···' }, ()=>{
        this._getBusNow()
      })
    })
  }
  UNSAFE_componentWillMount () {
    this._getParams()
  }
  componentWillUnmount () {
    clearTimeout(this._getInterval)
    this.refreshLine.remove()
  }
  // 定时器
  _getInterval
  // 获取路由传递信息
  _getParams () {
    let thisID = ''
    let direction = this.props.navigation.getParam('dirction') ? parseInt(this.props.navigation.getParam('dirction')) : 1
    if (!this.state.thisID) {
      thisID = this.props.navigation.getParam('thisID') ? this.props.navigation.getParam('thisID') : ''
    }
    this.setState({ lineID: this.props.navigation.getParam('id'), direction: direction, thisID: thisID }, ()=>{
      this._getBusInfo()
      this._getPrice()
      this._getNextTime()
      this._getNotice()
      if (this.state.thisID) {
        this._setIndex()
      }
    })
  }
  // 获取票价
  _getPrice() {
    getPrice(parseInt(this.state.lineID), this.state.direction).then(res=>{
      this.setState({
        price: res.price
      })
    })
  }
  // 获取下一班发车时间
  _getNextTime() {
    getNextBusTime(parseInt(this.state.lineID), this.state.direction).then(res=>{
      this.setState({
        nextTime: res.nextBusTime
      })
    })
  }
  _getNotice() {
    getNoticeDetail(parseInt(this.state.lineID), this.state.direction).then(res=>{
      this.setState({
        notice: { title: res.noticeTitle, content: res.noticeTitle, url: res.noticeUrl }
      })
    })
  }
  // 获取线路信息
  _getBusInfo () {
    ajaxAsync('/bus/bus/querybus', { SUB_ROUTEID: parseInt(this.state.lineID), BUS_DIRECTION: this.state.direction }).then(res=>{
      if (res.length > 0) {
        this.setState({
          changging: false,
          startStation: res.BUS_START_STATION,
          endStation: res.BUS_END_STATION,
          startTime: res.BUS_START_TIME,
          endTime: res.BUS_END_TIME,
          stations: res.BUS_STATIONS,
          segmentId: res.SEGMENT_ID
        }, ()=>{
          if (res.BUS_STATIONS && res.BUS_STATIONS.length > 0) {
            this._getBusNow()
          }
        })
      } else {
        this.setState({ showModel: false })
      }
    })
  }
  // 当前车辆位置
  _getBusNow () {
    if (this.state.thisID) {
      ajaxAsync('/bus/now/sameid3', { SUBROUTE_ID: parseInt(this.state.lineID), TYPE: this.state.direction, SAME_ID: this.state.thisID }).then(res=>{
        this.setState({ busNowApis: res.BUS_NOWAPIS, simpleDistance: res.SIMPLE_DISTANCES, showModel: false }, ()=>{
          this._setIndex()
          this._getInterval = setTimeout(()=>{
            this._getBusNow()
          }, 8000)
        })
      }).catch(err=>{
        LogUtils.warn(err)
        this.setState({ showModel: false })
        this._getInterval = setTimeout(()=>{
          this._getBusNow()
        }, 8000)
      })
    } else {
      ajaxAsync('/bus/now/lalo3', {
        SUBROUTE_ID: parseInt(this.state.lineID),
        TYPE: this.state.direction,
        LONGITUDE: 0,
        LATITUDE: 0
      }).then(res=>{
        this.setState({ thisID: res.STAITON_ID, busNowApis: res.BUS_NOWAPIS, simpleDistance: res.SIMPLE_DISTANCES, showModel: false }, ()=>{
          this._setIndex()
          this._getInterval = setTimeout(()=>{
            this._getBusNow()
          }, 8000)
        })
      }).catch(err=>{
        LogUtils.warn(err)
        this.setState({ showModel: false })
        this._getInterval = setTimeout(()=>{
          this._getBusNow()
        }, 8000)
      })
    }
  }
  // 设置当前站点序列
  _setIndex () {
    let thisIndex = 0
    let thisName = ''
    let lat = 0
    let lng = 0
    if (this.state.stations) {
      thisIndex = this.state.stations.length - 1
      this.state.stations.forEach((item, index)=>{
        if (item.STATION_ID === this.state.thisID) {
          thisIndex = index
          thisName = item.STATION_NAME
          lat = item.LATITUDE
          lng = item.LONGITUDE
        }
      })
    }
    this.setState({ thisIndex: thisIndex, thisName: thisName, lat: lat, lng: lng })
  }
  // 改变当前站点id
  _changeThisID (thisID, lat, lng, thisName) {
    clearTimeout(this._getInterval)
    this.setState({ thisID: thisID, lat: lat, lng: lng, thisName: thisName, showModel: true, modelText: '定位中···' }, ()=>{
      this._getBusNow()
    })
  }
  // 换向
  _changeDirction () {
    clearTimeout(this._getInterval)
    this.setState({ thisIndex: -1 })
    if (this.state.direction === 1) {
      this.setState({ direction: 2, changging: true, showModel: true, modelText: '换向中···', simpleDistance: [] }, ()=>{
        this._getBusInfo()
      })
    } else if (this.state.direction === 2) {
      this.setState({ direction: 1, changging: true, showModel: true, modelText: '换向中···', simpleDistance: [] }, ()=>{
        this._getBusInfo()
      })
    }
  }
  render () {
    return (
      <View style={[{ backgroundColor: '#F2F5F6', height: '100%' }]}>
        {this.state.stations && this.state.stations.length > 0 ? <View>{!this.state.changging
          ? <View style={[{ height: '100%' }, flex.flexV, flex.flexVc]}>
            {this.state.notice.title
              ? <BusNotice notice={new BusNoticeModel(this.state.notice.title, this.state.notice.content, this.state.notice.url)}></BusNotice>
              : null}
            <BusInfo changeDirction={this._changeDirction.bind(this)} price={this.state.price}
              lineName={this.props.navigation.getParam('name')}
              businfo={new BusInfoModel(this.state.startTime, this.state.endTime, this.state.startStation, this.state.endStation)}
              nextTime={this.state.nextTime}/>
            <BusStaion busNowApis={this.state.busNowApis} endTime={this.state.endTime}
              simpleDistance={this.state.simpleDistance} startTime={this.state.startTime}
              stations={this.state.stations}/>
            <BusNow busNowApis={this.state.busNowApis} changeThisID={this._changeThisID.bind(this)}
              stations={this.state.stations}
              thisID={this.state.thisID} thisIndex={this.state.thisIndex}
            />
            <BusNav lat={this.state.lat} lng={this.state.lng}
              thisId={this.state.thisID} type={this.state.direction}
              thisName={this.state.thisName} segmentId={this.state.segmentId} />
          </View>
          : null}</View> : <Error tipsText={'该方向没有线路'}></Error>}
        {this.state.showModel
          ? <Loading loading={this.state.modelText}></Loading> : null
        }
      </View>
    )
  }
}